package com.cfw.tree;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeNode;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

public class TreeSearchTestUtil {
	private static Logger logger = LoggerFactory.getLogger(TreeSearchTestUtil.class);

	private static Map<String, String> getMap(final String id) {
		return new HashMap<String, String>() {{ put("key", "key-" + id); put("value", "value-" + id); }};
	}

	private static DefaultMutableTreeNode getTree(final DefaultMutableTreeNode parentNode, final String seq) {
		return new DefaultMutableTreeNode() {{ setUserObject(getMap(seq)); parentNode.add(this); }};
	}
	
	// DefaultMutableTreeNode 테스트 소스 생성 - 시작
	public static DefaultMutableTreeNode getTreeNodeSource() {
		DefaultMutableTreeNode node = null;
		DefaultMutableTreeNode child = null;
		DefaultMutableTreeNode son = null;
		
		node = new DefaultMutableTreeNode();
		node.setUserObject(getMap("0"));
		
		for (int i = 1; i <= 2; i++) {
			child =	getTree(node, Integer.toString(i));
			
			for (int j = 1; j <= 2; j++) {
				son = getTree(child, Integer.toString(i) + "-" + Integer.toString(j));
				
				for (int k = 1; k <= 2; k++) {
					getTree(son, Integer.toString(i) + "-" + Integer.toString(j) + "-" + Integer.toString(k));
				}
			}
		}
		
		return node;
	}

	public static Node getXmlSource() {
		final InputStream stream = TreeSearchTestUtil.class.getResourceAsStream("/com/cfw/tree/tree-sample.xml");
		
		DocumentBuilder builder;
		Document doc = null;
		
		try {
			builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			doc = builder.parse(stream);
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return doc;
	}
	
	public static void logTree(final DefaultMutableTreeNode tree) {
		final Enumeration<TreeNode> allnode = tree.depthFirstEnumeration();
		
		while (allnode.hasMoreElements()) {
			final TreeNode eachnode = allnode.nextElement();
			logger.debug("node:" + eachnode.toString() + ",parent:" + (eachnode.getParent() == null ? "no parent" : eachnode.getParent().toString()));
		}
	}
	
}
